package com.losdun.weixin.security;

import com.losdun.common.constant.HttpStatus;
import com.losdun.common.exception.ServiceException;
import com.losdun.weixin.domain.WechatUser;
import com.losdun.weixin.security.vo.WxLoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/9/23
 **/
@Slf4j
public class WxSecurityUtils {

    /**
     * 用户ID
     **/
    public static Long getUserId(){
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            log.error("获取用户userId异常",e);
            throw new ServiceException("获取用户userId异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户openId
     * @return
     */
    public static String getOpenId(){
        try {
            return getLoginUser().getOpenId();
        } catch (Exception e) {
            log.error("获取用户openId异常",e);
            throw new ServiceException("获取用户openId异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户号码
     */
    public static String getPhone(){
        try {
            return getLoginUser().getWechatUser().getPhone();
        } catch (Exception e) {
            log.error("获取用户手机异常",e);
            throw new ServiceException("获取用户手机异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     * @return
     */
    public static WechatUser getWechatUser(){
        try {
            return getLoginUser().getWechatUser();
        } catch (Exception e) {
            log.error("获取用户信息异常",e);
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }
    /**
     * 获取用户
     **/
    public static WxLoginUser getLoginUser()
    {
        try
        {
            return (WxLoginUser) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            throw new ServiceException("获取登录用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }
}
